package edu.tec.mty.core.connection;

import java.util.Vector;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Dispatcher {

	class Command {
		
		private String command;
		private int maxAmount;
		
		public Command(String command, int maxAmount) {
			this.command = command;
			this.maxAmount = maxAmount;
		}
		
		public String getCommand() {
			return this.command;
		}
		
		public int getMaxAmount() {
			return this.maxAmount;
		}
		
	}
	
	private Connect connect;
	private Vector<Command> commands = new Vector<Command>();
	private final Lock accessBlock = new ReentrantLock();
	
	public Dispatcher(Connect connect) {
		this.connect = connect;
	}
	
	public boolean putCommandInQueue(String command, int maxAmount) {
		this.accessBlock.lock();
		this.commands.add(new Command(command, maxAmount));
		this.accessBlock.unlock();
		return true;
	}
	
	public void clearCommands() {
		this.accessBlock.lock();
		this.commands.clear();
		this.accessBlock.unlock();
	}
	
	public boolean sendCommand() {
		boolean returnValue = true;
		this.accessBlock.lock();
		if (this.commands.size() > 0) {
			String message = "";
			int sum = 0;
			do {			
				sum += this.commands.elementAt(0).getMaxAmount();
				if (sum < 2) {
					message += this.commands.elementAt(0).getCommand();
					this.commands.remove(0);
				}
			} while (sum < 2 && this.commands.size() > 0);
			this.connect.sendMessage(message);
			returnValue = false;
		}
		this.accessBlock.unlock();
		return returnValue;
	}
	
	//Test
	
	/*public static void main(String[] args) {
		Dispatcher dispatcher = new Dispatcher();
		dispatcher.putCommandInQueue("(move 0.0 0.0)", 1);
		dispatcher.putCommandInQueue("(change_view narrow low)", 0);
		dispatcher.putCommandInQueue("(turn 90)", 1);
		dispatcher.putCommandInQueue("(say hello)", 0);
		dispatcher.putCommandInQueue("(turn_neck -90)", 0);
		dispatcher.putCommandInQueue("(dash 100)", 1);
		dispatcher.sendCommand();
		dispatcher.sendCommand();
		dispatcher.sendCommand();
		dispatcher.putCommandInQueue("(say bye)", 0);
		dispatcher.sendCommand();
	}*/
	
}
